class Admins::DepartmentsController < Admins::BaseController
  before_action :set_department, only: [:show, :edit, :update, :destroy]

  def index
    @departments = Department.all.order("created_at ASC").page(params[:page])
  end

  def show
  end

  def new
    if params[:department].blank?
      @department = Department.new
    else
      @department = Department.new(department_params)
    end
  end

  def edit
  end

  def create
    @department = Department.new(department_params)
    if @department.save
        redirect_to :action => :index, notice: '部门创建成功'
    else
        flash[:error] = @department.errors.full_messages.join(",")
        redirect_to :action => :new,:department => @department.attributes
    end
  end

  def update
    if @department.update(department_params)
      flash[:success] = '部门更新成功'
      redirect_to :action => :index
    else
      flash[:error] = @department.errors.full_messages.join(",")
      render :edit
    end
  end

  def destroy
    @department.destroy
    flash[:success] = '部门删除成功'
    redirect_to :action => :index
  end

  private
    def set_department
      @department = Department.find(params[:id])
    end

    def department_params
      params.require(:department).permit(:name)
    end
end